import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Enumeration;

import javax.servlet.http.*;  // provides servlet functionality
import javax.servlet.*;	      // ditto
import javax.*;

public class DvdProcessor extends HttpServlet {
	
	private final static String REDIRECT_TO_CART_CODE 
		= "<meta http-equiv=\"REFRESH\" content=\"0;url=ShoppingCart\">";
	
	private final static String REDIRECT_TO_CHECKOUT_CODE
		= "<meta http-equiv=\"REFRESH\" content=\"0;url=CustomerInformation\">";

	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException
	{
		doPost(request, response);
	}
	
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException
	{
		if (!Bridge.hasBeenToMainPage(request.getSession(), response.getWriter()))
		{
			return;
		}
		
		PrintWriter out = response.getWriter();
		try
		{
			Class.forName("org.postgresql.Driver").newInstance();
			Connection connection = DriverManager.getConnection(
				"jdbc:postgresql://localhost/fabflixs", "testuser", "testpass");	
			HttpSession session = request.getSession();
			
			session.setAttribute(Constants.wantToGoToCartAttributeName, new Boolean(true));
			
			if (buttonPushed(request).equals("UpdateButton"))
				session.setAttribute(Constants.viaUpdateButtonAttributeName, new Boolean(true));
			else
				session.setAttribute(Constants.viaUpdateButtonAttributeName, new Boolean(false));
			
			String movieId = request.getParameter("movieId");
			if (movieId != null) // we're adding a single movie
			{
				Statement select = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
				ResultSet result = select.executeQuery("Select * from movies where id = " + movieId);
								
				if (result.next())
				{
					DVD dvdToReturn = new DVD(Integer.parseInt(movieId), result.getString(2),
							result.getInt(3), result.getString(7) + " " + result.getString(4));
					
					session.setAttribute(Constants.dvdToAddAttributeName, dvdToReturn);
					session.removeAttribute(Constants.dvdsToSetAttributeName);
					
					
					out.print("<html><head><title>Processing...</title>"
							+ REDIRECT_TO_CART_CODE + "</head>"
							+ "<body>" 
							+ "</body>" 
							+"</html>");					
				}				
			}
			else //we're updating (potentially) a bunch of movies, from within the cart 
			{
				ArrayList<DVD> dvdsToSet = new ArrayList<DVD>(); 
				Enumeration<String> parameterNameEmun = request.getParameterNames();
				int counter = 0;
				while (parameterNameEmun.hasMoreElements())
				{
					String id = parameterNameEmun.nextElement().trim();
					if (!isNumber(id))
						continue;
					
					CartOfItems cart = (CartOfItems)session.getAttribute(Constants.cartAttributeName);
					CartOfItems tempCart = new CartOfItems(cart);
					DVD filmToSet = new DVD(tempCart.getDvdById(Integer.parseInt(id)));
					int quantity = Integer.parseInt(request.getParameter(id).trim());
					filmToSet.setQuantity(quantity);
					
					dvdsToSet.add(filmToSet);
				}
				
				System.out.println("In DvdProcessor: dvdsToSet=" + dvdsToSet);
				
				session.setAttribute(Constants.dvdsToSetAttributeName, dvdsToSet);
				session.removeAttribute(Constants.dvdToAddAttributeName);
								
				String redirectCode = REDIRECT_TO_CART_CODE;
				if (buttonPushed(request).equals("CheckoutButton"))
				{
					redirectCode = REDIRECT_TO_CHECKOUT_CODE;
				}
				
				out.print("<html><head><title>Processing...</title>"
						+ redirectCode + "</head>"
						+ "<body>"
						//+ buttonPushed(request)
						+ "</body>" 
						+"</html>");
			}
			
		} catch (Exception e) 
		{
			out.println("Exception: " + e.getMessage());
		}
	}
	
	private boolean isNumber(String str)
	{
		try {Integer.parseInt(str);}
		catch (Exception e)
		{
			return false;
		}
		return true;
	}
	
	private String buttonPushed(HttpServletRequest request)
	{
		Enumeration<String> paramNames = request.getParameterNames();
		while (paramNames.hasMoreElements())
		{
			String param = paramNames.nextElement();
			if(param.endsWith(".x"))
				return param.substring( 0, param.length() - 2 );
		}
		
		return "none";
	}
	
}
